package com.dg.admodule.adbutton;

import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;

import com.dg.admodule.AdConstants;
import com.dg.admodule.AdModule;
import com.smaato.SmaatoAPICallback;
import com.smaato.SmaatoAd;

public class AdButton extends Field implements SmaatoAPICallback{
	private SmaatoAdField adField;
	private boolean isFocused = false;
	
	public AdButton(long style){
		super(style | Field.EDITABLE | Field.FOCUSABLE);
		//this.adField = new SmaatoAdField(null);
		//add(this.adField);
//		UiApplication.getUiApplication().invokeLater(new Runnable() {
//			
//			public void run() {
//				startAdRequesting();
//			}
//		});
	}

	public void getAdNotifySuccess() {
			AdModule.getInstance().setIRequestOutstanding(false);
			SmaatoAd ad = AdModule.getInstance().getSmaatoApi().showAd();
			this.adField.setSmaatoAd(ad);
	}

	public void getAdNotifyError(int errorCode, String errorString) {
		AdModule.getInstance().setIRequestOutstanding(false);
		
		String message = "Error " + errorCode + ". " + errorString;
		System.out.println(message);
	}
	
	public int getPreferredWidth() {
		// TODO Auto-generated method stub
		return AdConstants.width;
	}
	
	public int getPreferredHeight() {
		// TODO Auto-generated method stub
		return AdConstants.height;
	}
	
	public void startAdRequesting(){
		if (AdModule.getInstance().getSmaatoApi() != null && this.adField != null){
			AdModule.getInstance().setIRequestOutstanding(true);
			AdModule.getInstance().getSmaatoApi().getAd(this);
		}
	}
	
	protected boolean navigationClick(int status, int time) {
		
		return super.navigationClick(status, time);
	}
	
	protected void onFocus(int direction) {
		if (!this.isFocused){
			this.isFocused = true;
			invalidate();
		}
	}
	
	protected void onUnfocus() {
		if (this.isFocused){
			this.isFocused = false;
			invalidate();
		}
	}

	protected void layout(int width, int height) {
		// TODO Auto-generated method stub
		setExtent(Math.min(width, getPreferredWidth()), Math.min(height, getPreferredHeight()));
	}

	protected void paint(Graphics graphics) {
		if (this.isFocused){
			graphics.setColor(Color.RED);
			graphics.drawRect(0, 0, AdConstants.width, AdConstants.height);
		} else {
			graphics.setColor(Color.GREEN);
			graphics.drawRect(0, 0, AdConstants.width, AdConstants.height);
		}
	}
	
	//protected void paintBackground(Graphics arg0) {}
	protected void drawFocus(Graphics graphics, boolean on) {}
}
